package cn.bincker.mycaptcha.basic.impl;

import cn.bincker.mycaptcha.basic.VerifyFailHandler;
import cn.bincker.mycaptcha.basic.entity.CaptchaResponseMessage;
import cn.bincker.mycaptcha.basic.exception.CaptchaExpireException;
import cn.bincker.mycaptcha.basic.exception.CaptchaVerifyFailException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class DefaultVerifyFailHandler implements VerifyFailHandler {
    private final ObjectMapper objectMapper;

    public DefaultVerifyFailHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, CaptchaVerifyFailException exception) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        if(CaptchaExpireException.class.isAssignableFrom(exception.getClass())){
            objectMapper.writeValue(response.getWriter(), new CaptchaResponseMessage("验证码超时"));
            return;
        }
        objectMapper.writeValue(response.getWriter(), new CaptchaResponseMessage("验证码错误"));
    }
}
